package com.eboss.sbs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;

import com.eboss.sbs.R;
import com.eboss.sbs.activity.base.BaseActivity;
import com.eboss.sbs.adapter.ChooseOptionAdapter;
import com.eboss.sbs.adapter.TransactionListAdapter;
import com.eboss.sbs.config.Config;
import com.eboss.sbs.enums.EnumConsts;
import com.eboss.sbs.http.API;
import com.eboss.sbs.http.HttpCallback;
import com.eboss.sbs.model.TransactionEntity;
import com.eboss.sbs.model.TransactionListEntity;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.utils.TimeUtil;
import com.mytools.tool.views.MyListView;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TransactionActivity extends BaseActivity implements OnItemClickListener {

	private int TYPE_TIME_OPTION = 1;
	private int TYPE_PAY_OPTION = 2;
	
	private final int REQUEST_CODE_QUERYDATE_FROM = 1;
	private final int REQUEST_CODE_QUERYDATE_TO = 2;
	
	private PullToRefreshScrollView pullToRefreshScrollView;
	
	private Date panel_dateFrom = new Date();
	private Date panel_dateTo = new Date();
	private Date query_dateFrom = panel_dateFrom;
	private Date query_dateTo = panel_dateTo;
	
	private MyListView listview;
	private TransactionListAdapter adapter;
	private List<TransactionEntity> datas;
	
	private AlertDialog dialog_panel;
	
	//日期选择
	private GridView gv_option_time;
	private ArrayList<String> time_values = new ArrayList<String>(){
		{
			add(EnumConsts.TimeZoneType.SEVENDAY.getName());
			add(EnumConsts.TimeZoneType.MONTH.getName());
			add(EnumConsts.TimeZoneType.MONTHLAST.getName());
			add(EnumConsts.TimeZoneType.CUSTOM.getName());
		}
	};
	private BitSet time_marks = new BitSet(time_values.size());
	private ChooseOptionAdapter adapter_time;
	private int timeType = EnumConsts.TimeZoneType.CUSTOM.getCode();
	private TextView tv_date_to, tv_date_from;
	private LinearLayout ly_time_zone;
	
	//支付方式
	private GridView gv_option_paytype;
	private ArrayList<String> paytype_values = new ArrayList<String>(){
		{
			add(EnumConsts.SqbPayChannel.ALL.getName());
			add(EnumConsts.SqbPayChannel.CARD_MEMO.getName());
			add(EnumConsts.SqbPayChannel.CASH_MEMO.getName());
			add(EnumConsts.SqbPayChannel.WEIXIN.getName());
			add(EnumConsts.SqbPayChannel.ALIPAY.getName());
			add(EnumConsts.SqbPayChannel.WALLET.getName());
			add(EnumConsts.SqbPayChannel.CARD.getName());
		}
	};
	private BitSet paytype_marks = new BitSet(paytype_values.size());
	private ChooseOptionAdapter adapter_paytype;
	private int payType = EnumConsts.SqbPayChannel.ALL.getType();
	
	private int page = 1;
	private int rows = Config.ROWS;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mActivity = this;
		setContentView(R.layout.activity_transaction);
		super.onCreate(savedInstanceState);
		initView();
	}
	
	private void initView(){
		showView(R.id.titleback_btn_back, true);
		setTvText(R.id.tv_title, "店铺交易数据 ");
		showView(R.id.next_sure, true);
		setTvText(R.id.next_sure, "筛选");
		
		String from = TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日");
		setTvText(R.id.tv_date_choose, from);
		
		pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pullToRefreshScrollView);
		pullToRefreshScrollView.setOnRefreshListener(new MyOnRefreshListener());
		pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
		
		datas = new ArrayList<TransactionEntity>();
		listview = (MyListView)findViewById(R.id.listview);
		listview.setOnItemClickListener(this);
		adapter = new TransactionListAdapter(this, datas);
		
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);
		findViewById(R.id.next_sure).setOnClickListener(this);
		findViewById(R.id.ly_previous).setOnClickListener(this);
		findViewById(R.id.ly_next).setOnClickListener(this);
		
		listview.setAdapter(adapter);
		showNextDayBtn();
		
		getdata();
	}
	
	class MyOnRefreshListener implements PullToRefreshBase.OnRefreshListener2<ScrollView> {
		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
			String label = DateUtils.formatDateTime(mActivity, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			refreshData();
		}
		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			page++;
			getdata();
		}
	}
	
	private void refreshData(){
		datas.clear();
		page = 1;
		getdata();
	}
	
	private void getdata(){
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sid", mApp.getLoginEntity().getSid());
		if(payType!= EnumConsts.SqbPayChannel.ALL.getType()){params.put("payType", payType);}
		else{params.put("payType", "");}
		
		params.put("datefrom", TimeUtil.getStringFromDate(query_dateFrom, "yyyy-MM-dd"));
		params.put("dateto", TimeUtil.getStringFromDate(query_dateTo, "yyyy-MM-dd"));
		params.put("pagenum", page);
		params.put("pagesize", rows);
		
		API.http_post(this, API.SHOPCOST_LIST, params, new HttpCallback<TransactionListEntity>(this) {
			@Override
			public void onSuccess(int statusCode, TransactionListEntity data) {
				if(data!=null){
					if(page==1){
						setTvText(R.id.tv_num, data.getNum()+"笔");
						setTvText(R.id.tv_total_money, StringUtil.getMoneyString(data.getTotalMoney())+"元");
						setTvText(R.id.tv_totalReal_money, StringUtil.getMoneyString(data.getTotalReal())+"元");
					}
					 List<TransactionEntity> tmp_datas = data.getConsumptions();
					 if(tmp_datas==null||tmp_datas.size()==0||tmp_datas.size()<rows){
						if(tmp_datas==null||tmp_datas.size()==0){
							toast("没有更多数据");
						}
						pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
					 }
					 if(tmp_datas!=null&&tmp_datas.size()>0){
						 datas.addAll(tmp_datas);
					 }
				}
				adapter.notifyDataSetChanged();
				pullToRefreshScrollView.onRefreshComplete();
			}
			
			@Override
			public void onFailure(int code, String message) {
				pullToRefreshScrollView.onRefreshComplete();
				super.onFailure(code, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<TransactionListEntity>() {
				};
			}
		});
		
	}
	
	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
			case R.id.titleback_btn_back:
				finish();
				break;
			case R.id.next_sure:
				showPanel();
				break;
			case R.id.ly_previous:
				query_dateFrom = TimeUtil.getDateFromDate(query_dateFrom, -1);
				query_dateTo = query_dateFrom;
				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				timeType = EnumConsts.TimeZoneType.CUSTOM.getCode();
				payType = EnumConsts.SqbPayChannel.ALL.getType();
				setTvText(R.id.tv_date_choose, TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日"));
				showNextDayBtn();
				refreshData();
				break;
			case R.id.ly_next:
				query_dateFrom = TimeUtil.getDateFromDate(query_dateFrom, 1);
				query_dateTo = query_dateFrom;
				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				timeType = EnumConsts.TimeZoneType.CUSTOM.getCode();
				payType = EnumConsts.SqbPayChannel.ALL.getType();
				setTvText(R.id.tv_date_choose, TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日"));
				showNextDayBtn();
				refreshData();
				break;
			case R.id.tv_date_from:
				intent.setClass(mActivity, ChooseDateActivity.class);
				String tmp_date_str_from = TimeUtil.getStringFromDate(panel_dateFrom==null?(new Date()):panel_dateFrom, ChooseDateActivity.FORMAT_DATE);
				intent.putExtra(ChooseDateActivity.PARA_SELECTED_DATE, tmp_date_str_from);
				intent.putExtra("chooseType", ChooseDateActivity.CHOOSE_BEFORE_TODAY);
				intent.putExtra("toDate", TimeUtil.getStringFromDate(panel_dateTo, ChooseDateActivity.FORMAT_DATE));
				startActivityForResult(intent, REQUEST_CODE_QUERYDATE_FROM);
				break;
			case R.id.tv_date_to:
				intent.setClass(mActivity, ChooseDateActivity.class);
				String tmp_date_str_to = TimeUtil.getStringFromDate(panel_dateTo==null?(new Date()):panel_dateTo, ChooseDateActivity.FORMAT_DATE);
				intent.putExtra(ChooseDateActivity.PARA_SELECTED_DATE, tmp_date_str_to);
				intent.putExtra("chooseType", ChooseDateActivity.CHOOSE_BEFORE_TODAY);
				intent.putExtra("fromDate", TimeUtil.getStringFromDate(panel_dateFrom, ChooseDateActivity.FORMAT_DATE));
				startActivityForResult(intent, REQUEST_CODE_QUERYDATE_TO);
				break;
			case R.id.btn_filter_confirm:
				
				if(dialog_panel!=null){dialog_panel.dismiss();}
				
				if(timeType== EnumConsts.TimeZoneType.CUSTOM.getCode()){
					query_dateFrom = panel_dateFrom;
					query_dateTo = panel_dateTo;
				}
				else{
					Date today = new Date();
					if(timeType== EnumConsts.TimeZoneType.SEVENDAY.getCode()){
						query_dateFrom = TimeUtil.getDateFromDate(today, -7);
						query_dateTo = TimeUtil.getDateFromDate(today, -1);
					}
					else if(timeType== EnumConsts.TimeZoneType.MONTH.getCode()){
						query_dateFrom = TimeUtil.getDateFromString(TimeUtil.getCurrentDateString("yyyyMM")+"01", "yyyyMMdd");
						query_dateTo = TimeUtil.getDateFromDate(today, 0);
					}
					else if(timeType== EnumConsts.TimeZoneType.MONTHLAST.getCode()){
						Date query_dateTo_tmp = TimeUtil.getDateFromString(TimeUtil.getCurrentDateString("yyyyMM")+"01", "yyyyMMdd");
						query_dateTo = TimeUtil.getDateFromDate(query_dateTo_tmp, -1);
						query_dateFrom = TimeUtil.getDateFromString(TimeUtil.getStringFromDate(query_dateTo, "yyyyMM")+"01", "yyyyMMdd");
					}
				}
				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				String from = TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日");
				String to = TimeUtil.getStringFromDate(query_dateTo, "yyyy年MM月dd日");
				boolean checkshow = from.equals(to);
				showView(R.id.ly_date_chooser, checkshow?true:false);
				showView(R.id.ly_date_show, checkshow?false:true);
				setTvText(R.id.tv_date_choose, from);
				setTvText(R.id.tv_date_show, from+" - "+to);
				
				showNextDayBtn();
				refreshData();
				
				break;
			default:break;
		}
		super.onClick(v);
	}
	
	private void showPanel() {
		dialog_panel = new AlertDialog.Builder(mActivity).create();
		dialog_panel.show();
		Window window = dialog_panel.getWindow();
		
		WindowManager.LayoutParams lp =window.getAttributes();
		lp.x=0;
		lp.y=150;
		
		// 设置布局
		window.setContentView(R.layout.dialog_transaction_filter);
		// 设置宽高
		window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		// 设置弹出的动画效果
		// show at bottom
		window.setGravity(Gravity.TOP); 
		
		ly_time_zone = (LinearLayout) window.findViewById(R.id.ly_time_zone);
		tv_date_from = (TextView) window.findViewById(R.id.tv_date_from);
		tv_date_to = (TextView) window.findViewById(R.id.tv_date_to);
		tv_date_from.setOnClickListener(this);
		tv_date_to.setOnClickListener(this);
		
		window.findViewById(R.id.btn_filter_confirm).setOnClickListener(this);
		
		gv_option_time = (GridView) window.findViewById(R.id.gv_option_time);
		adapter_time = new ChooseOptionAdapter(mActivity, time_values, time_marks);
		gv_option_time.setAdapter(adapter_time);
		gv_option_time.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				adapterNotify(TYPE_TIME_OPTION, arg2);
			}
		});
		
		gv_option_paytype = (GridView) window.findViewById(R.id.gv_option_paytype);
		adapter_paytype = new ChooseOptionAdapter(mActivity, paytype_values, paytype_marks);
		gv_option_paytype.setAdapter(adapter_paytype);
		gv_option_paytype.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				adapterNotify(TYPE_PAY_OPTION, arg2);
			}
		});
		
		reflashPanel();
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=RESULT_OK)return;
		switch (requestCode) {
			case REQUEST_CODE_QUERYDATE_FROM:
				String a = data.getStringExtra(ChooseDateActivity.PARA_SELECTED_DATE);
				panel_dateFrom = TimeUtil.getDateFromString(a, ChooseDateActivity.FORMAT_DATE);
				tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
				break;
			case REQUEST_CODE_QUERYDATE_TO:
				String b = data.getStringExtra(ChooseDateActivity.PARA_SELECTED_DATE);
				panel_dateTo = TimeUtil.getDateFromString(b, ChooseDateActivity.FORMAT_DATE);
				tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
				break;
			default: break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void adapterNotify(int adapterType, int index){
		if(adapterType==TYPE_TIME_OPTION){
			timeType = EnumConsts.TimeZoneType.getCodeByName(time_values.get(index));
			reflashPanel();
		}
		else if(adapterType==TYPE_PAY_OPTION){
			payType = EnumConsts.SqbPayChannel.getTypeByName(paytype_values.get(index));
			reflashPanel();
		}
	}
	
	private void reflashPanel(){
		int size1 = time_values.size();
		for (int i = 0; i < size1; i++) {
			int type_tmp = EnumConsts.TimeZoneType.getCodeByName(time_values.get(i));
			time_marks.set(i, type_tmp==timeType?true:false);
		}
		ly_time_zone.setVisibility(timeType== EnumConsts.TimeZoneType.CUSTOM.getCode()?View.VISIBLE:View.GONE);
		if(timeType== EnumConsts.TimeZoneType.CUSTOM.getCode()){
			tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
			tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
		}
		
		int size2 = paytype_values.size();
		for (int i = 0; i < size2; i++) {
			int type_tmp = EnumConsts.SqbPayChannel.getTypeByName(paytype_values.get(i));
			paytype_marks.set(i, type_tmp==payType?true:false);
		}
		
		adapter_time.notifyDataSetChanged();
		adapter_paytype.notifyDataSetChanged();
	}
	
	private void showNextDayBtn(){
		String a = TimeUtil.getStringFromDate(query_dateFrom, "yyyyMMdd");
		String b = TimeUtil.getStringFromDate(query_dateTo, "yyyyMMdd");
		String c = TimeUtil.getCurrentDateString("yyyyMMdd");
		showView(R.id.ly_next, !(a.equals(b)&&b.equals(c)));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		view.setBackgroundResource(R.color.gray);

		Intent intent = new Intent();
		intent.setClass(mActivity, TradeDetailActivity.class);
		intent.putExtra("tradeOrderNo", datas.get(position).getTradeOrderNo());
		startActivity(intent);
	}
	
}
